package cn.yunyichina.provider.pay.pacity.service.impl;

import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.dto.pacity.PacityAccessTokenRequestDTO;
import cn.yunyichina.provider.iface.entity.dto.pacity.PacityAccessTokenResponseDTO;
import cn.yunyichina.provider.pay.pacity.constant.PacityConstant;
import cn.yunyichina.provider.pay.pacity.constant.ResponseEnum;
import cn.yunyichina.provider.pay.pacity.service.BaseService;
import cn.yunyichina.provider.pay.pacity.service.PacityAuthService;
import cn.yunyichina.utils.commons.HttpContentType;
import cn.yunyichina.utils.commons.HttpUtil;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * Created by Lullaby on 2017/6/14.
 */
@Service
public class PacityAuthServiceImpl extends BaseService implements PacityAuthService {

    private static final Logger logger = LoggerFactory.getLogger(PacityAuthServiceImpl.class);

    /**
     * 获取平安开放平台授权访问令牌
     *
     * @param requestDTO
     * @return
     */
    public ResCommon<PacityAccessTokenResponseDTO> getPacityAccessToken(PacityAccessTokenRequestDTO requestDTO) {
        logger.info("PacityAuthServiceImpl.getPacityAccessToken.requestDTO -> {}", JsonUtils.toJsonString(requestDTO));

        try {
            String postContent = HttpUtil.buildFormUrlEncodedParams(JsonUtils.parseObject(requestDTO, Map.class));
            logger.info("PacityAuthServiceImpl.getPacityAccessToken.postContent -> {}", postContent);

            String postResponse = HttpUtil.httpBasicPost(
                    getConfig(PacityConstant.PACITY_HTTP_BASIC_USERNAME),
                    getConfig(PacityConstant.PACITY_HTTP_BASIC_PASSWORD),
                    postContent, getConfig(PacityConstant.PACITY_URL_AUTH), HttpContentType.FORMURLENCODED
            );

//            String postResponse = "{" +
//                    "\"returnCode\":\"SUCCESS\"," +
//                    "\"returnMsg\":\"请求失败\"," +
//                    "\"timestamp\":\"2017-05-16 08:08:08\"," +
//                    "\"sign\":\"BUkqCGRO9fH90Vci3hOH01BfYnbhJz\"," +
//                    "\"resultCode\":\"FAIL\"," +
//                    "\"errcode\":\"WTF\"," +
//                    "\"errcodeDesc\":\"请求结果出错\"," +
//                    "\"accessToken\":\"publicpBa869cad0990e4e17a57ecf7c5469a4b2\"," +
//                    "\"userId\":\"u201705161030001\"" +
//                    "}";
            logger.info("PacityAuthServiceImpl.getPacityAccessToken.postResponse -> {}", postResponse);

            PacityAccessTokenResponseDTO accessTokenResponse = JSON.parseObject(postResponse, PacityAccessTokenResponseDTO.class);
            logger.info("PacityAuthServiceImpl.getPacityAccessToken.accessTokenResponse -> {}", JSON.toJSONString(accessTokenResponse));

//            accessTokenResponse.setError(null);
//            accessTokenResponse.setError_description(null);
//
//            accessTokenResponse.setAccessToken("access_token");
//            accessTokenResponse.setExpiresIn("15m");
//            accessTokenResponse.setTokenType("hahaha");
//            accessTokenResponse.setScope("scope");

            if (accessTokenResponse.isSuccess()) {
                return new ResCommon<PacityAccessTokenResponseDTO>().buildResult(accessTokenResponse);
            } else {
                return new ResCommon<PacityAccessTokenResponseDTO>().buildResultCodeAndMessageAndResult(
                        ResponseEnum.PACITY_ACCESS_TOKEN_FAILURE.getCode(),
                        ResponseEnum.PACITY_ACCESS_TOKEN_FAILURE.getMessage(),
                        accessTokenResponse
                );
            }
        } catch (Exception e) {
            logger.error("PacityAuthServiceImpl.getPacityAccessToken.Exception", e);

            return new ResCommon<PacityAccessTokenResponseDTO>().buildResultCodeAndMessage(
                    ResponseEnum.PACITY_ACCESS_TOKEN_EXCEPTION.getCode(),
                    ResponseEnum.PACITY_ACCESS_TOKEN_EXCEPTION.getMessage()
            );
        }
    }

}
